package com.dl.ribbonconfig;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: user
 * @Date: 2021/8/31 15:24
 * @Description:
 */
public class NacosSameClusterWeightedRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties discoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        // 获取配置文件中所配置的集群名称
        String clusterName = discoveryProperties.getClusterName();

        BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
        String serviceId = baseLoadBalancer.getName();

        //获取服务发现的相关api
        NamingService namingService = discoveryProperties.namingServiceInstance();
        try {
            // 获取该微服务的所有健康实例
            List<Instance> instances = namingService.selectInstances(serviceId, true);
            instances.stream().filter(d -> Objects.equals(d.getClusterName(), clusterName)).collect(Collectors.toList());
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return null;
    }
}
